/**
* @desc:  人员管理-下发名单
* @author qiankui
* @date 2023-4-21 16:36:42
*/
<template>
    <el-dialog :close-on-click-modal="false" :visible="distributeFlag" class="zdy-dialog" width="1000px" :title="$t('Send list')"
               :before-close="handleCloseDialog">
        <div class="el-dialog-div">
            <!--组织树-->
            <div element-loading-background="rgba(255, 255, 255, 0.8)" class="treeView" v-loading="orgInfoTreeLoading">
                <!--<p>组织</p>-->
                <div class="searchView centerPersonView">
                    <el-input
                            size="small"
                            class="searchInput"
                            prefix-icon="el-icon-search"
                            :placeholder="placeholderTips"
                            v-model="filterTextOrg">
                    </el-input>
                </div>

                <vl-tree id="leftTree" empty-text="没有人员可以下发，请添加人员。" node-key="id"
                         :default-expanded-keys="defaultExpandedArr"
                         :filter-method="filterNode" ref="orgInfoTree" class="orgTree" show-checkbox
                         :height="485" :props="orgInfoProps" :data="orgInfo" >
                    <div class="custom-tree-node" slot-scope="{ node, data }">
                       <span>
                           <i v-if="data.sex==undefined&&data.id!=-200" class="orgIcon iconfont-KUI icon-modules"></i>
                           <i v-if="data.sex!==undefined" :class="{'female':data.sex==1}"
                              class="el-icon-user-solid userIcon" style="margin-right:5px">
                           </i>
                           <span style="width: 120px;display: inline-block;vertical-align: bottom" class="ellipsis" :title="node.label">{{ node.label }}</span>
                       </span>
                        <span v-if="data.id!=-200">
                            <el-tag style="margin-right: 3px" type="info" size="mini" v-if="data.sex==undefined">{{getOrgPersionCountFn(data.children)}}</el-tag>
                        </span>

                    </div>
                </vl-tree>


                <el-button :loading="moveLoading" id="move" @click="moveRight" icon="el-icon-d-arrow-right" circle></el-button>
            </div>
            <!--<el-button @click="getCheckedNodes">通过 node 获取</el-button>-->
            <!--<el-button @click="getCheckedKeys">通过 key 获取</el-button>-->
            <!--已选人员-->
            <div class="treeView person">
                <!--<p>人员</p>-->
                <div class="searchView">
                    <!--已选-->
                    <span style="line-height: 35px">{{this.i18n.t('selected')}} {{selectedPersonList.length}}</span>
                    <!--清空-->
                    <i v-if="selectedPersonList.length" :title="$t('empty')"@click="clearAll" class="el-icon-delete clearBtn"></i>
                </div>
                <div class="personView filter-tree">

                    <vl-tree empty-text="请在左侧选择人员" node-key="id" ref="selectedTree" class="personList"
                             :height="485" :props="orgInfoProps" :data="selectedPersonList" >
                        <div class="custom-tree-node" slot-scope="{ node, data }">

                            <span>
                                <span style="width: 120px;display: inline-block" :title="node.label" class="noDepartmentName ellipsis">{{ node.label }}</span>
                                <el-tag style="margin-right: 3px" type="info" size="mini" v-if="data.sex==undefined">{{getOrgPersionCountFn(data.children)}}</el-tag>
                                <!--<el-tag type="info" size="mini" v-if="data.sex==undefined">{{data.children.length}}</el-tag>-->
                            </span>
                            <span>
                                <!--删除-->
                                <i @click="deleteSelectedList(data)" class="el-icon-delete treeToolIcon" :title="$t('delete')"></i>
                            </span>

                        </div>
                    </vl-tree>
                    <ul style="" v-if="false">

                        <!--<li v-for="(item,index) in selectedPersonList" :key="item.id" class="personList">-->
                            <!--<span class="centerName">{{item.name}}</span>-->
                            <!--&lt;!&ndash;删除&ndash;&gt;-->
                            <!--<i :title="$t('delete')" @click="deleteSelectedList(item)" class="el-icon-error"></i>-->
                        <!--</li>-->
                        <!--<p class="el-tree__empty-text" v-if="!selectedPersonList.length">{{this.i18n.t('No data available')}}</p>-->
                    </ul>
                </div>
            </div>
            <!--在线设备列表-->
            <div class="treeView">
                <!--<p>在线设备</p>-->
                <div class="searchView centerPersonView">
                    <el-input
                            class="searchInput"
                            size="small"
                            prefix-icon="el-icon-search"
                            :placeholder="placeholderTips"
                            v-model="filterTextDev">
                    </el-input>
                    <!--全部-->
                    <el-checkbox @change="rightPersonChange" :disabled="!devList.length" v-model="rightPersonAll">{{this.i18n.t('All')}}</el-checkbox>
                </div>
                <el-tree
                    id="devListTree"
                        class="filter-tree"
                        show-checkbox
                        :element-loading-background="loadingBG"
                        v-loading="onlinedevLoading"
                        :empty-text="$t('No online devices')"
                        :data="devList"
                        node-key="id"
                        :check-on-click-node="true"
                        :props="devListProps"
                        default-expand-all
                        :filter-node-method="filterNodeDev"
                        ref="devTree">
                </el-tree>
            </div>
        </div>
        <br>
        <div class="footBtnBox">
            <!--取消-->
            <el-button size="small" type="handle" @click="handleCloseDialog">{{this.i18n.t('Cancel')}}</el-button>
            <!--保存-->
            <el-button size="small" type="primary" :loading="saveloading" @click="submitForm">{{this.i18n.t('save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {deviceinfoGetallonlinedevices} from "@/api/pcmj/sbsj";
    import {personnelinfoSendpersondata} from "@/api/pcmj/zzxx";
    import {filterTreeData,traverseDep} from './utils.js'
    import {getdepartmenttree} from "@/api/pcmj/zzxx";
    import { getGuid} from "@/assets/common/js/global";
    export default {
        name: "distributeList",
        components: {},
        props: {
            distributeFlag: {
                type: Boolean,
                default: false
            },
            editTableRow: {
                type: Array,
                defautl: []
            }
        },
        watch: {
            filterTextOrg(val) {
                this.$refs.orgInfoTree.filter(val);
            },
            filterTextDev(val) {
                this.$refs.devTree.filter(val);
            }
        },
        data() {
            return {
                defaultExpandedArr: [],
                getOrgPersionCountFn:null,
                orgInfoHeight:0,
                orgInfoDisplay:false,
                rightPersonAll:false,
                saveloading:false,
                moveLoading:false,
                onlinedevLoading:false,
                filterTextOrg:'',
                filterTextDev:'',
                loadingBG:'rgba(255, 255, 255, 0.8)',
                orgInfoTreeLoading:false,
                devList:[],
                selectedPersonList:[],
                selectedDevList:[],
                orgInfo:[],
                placeholderTips:this.i18n.t('Please enter keywords'),
                filterText:'',
                orgInfoProps:{
                    value:"id",
                    children: 'children',
                    label: 'name',
                    disabled: function(data, node) {
                        // console.log(132,data,data.sex, node);
                        // return true
                        // 禁用复选框选项
                        if (data.sex==undefined) {
                            // return true
                            return false
                        }else{
                            return false
                        }
                    }
                },
                devListProps: {
                    children: 'children',
                    label: 'deviceName',
                    disabled: function(data, node) {
                        // console.log(132,data,data.sex, node);
                        // return true
                        // 禁用复选框选项
                        // if (data.sex==undefined) {
                        //     return true
                        // }else{
                        //     return false
                        // }
                    }
                },
                leftPersionIdList:[],
                orgTreeSelected:[]
            }
        },
        methods: {
            // 递归检测父元素或自己是否符合条件
            filterNodeAndParent (param) {
                console.log(189,param);
                param.map( item => {
                    if(item.children){

                        // this.leftPersionIdList.push(item.id); // 保存每次遍历的结果
                        this.filterNodeAndParent(item.children);
                    }

                    this.leftPersionIdList.push(item.id); // 保存每次遍历的结果
                    // if ((item.children).length > 0) {
                    //     this.recursion(item.children);
                    // }

                });
            },
            leftPersonChange(val){

                console.log('this.orgInfo',this.orgInfo);
                // console.log(val,this.orgInfo);
                // console.log(this.$refs.orgInfoTree.getHalfCheckedKeys());
                if(val){
                    console.log(186,this.$refs.orgInfoTree.getCheckedNodes());
                    this.$nextTick(() => {
                        var selectedAll=[]
                        if (this.orgInfo.length){
                            this.orgInfo.map(item=>{
                                selectedAll.push(item.id)
                            })
                        }
                        console.log(193,this.$refs.orgInfoTree);
                        console.log('全部父节点ID',selectedAll);
                        console.log(this.$refs.orgInfoTree.setCheckedKeys(selectedAll));
                        // this.$refs.orgInfoTree.setCurrentKey(this.orgInfo);
                    })

                }else{
                    this.$refs.orgInfoTree.setCheckedKeys([]);
                }
            },
            rightPersonChange(val){
                console.log(val,this.devList);
                if(val){
                    this.$refs.devTree.setCheckedNodes(this.devList);
                }else{
                    this.$refs.devTree.setCheckedKeys([]);
                }
            },
            // 发送人员信息到设备
            personnelinfoSendpersondata(params){
                personnelinfoSendpersondata(params).then((res) => {
                    if (res.code === 200) {
                        // 下发成功
                        this.W.$tips("success", this.i18n.t('Successfully distributed'));
                        // 关闭弹窗
                        this.$emit("update:distributeFlag",false);
                    }
                }).catch().finally(() => {
                    this.saveloading=false
                })
            },
            // 获取在线设备
            deviceinfoGetallonlinedevices(){
                this.onlinedevLoading=true
                deviceinfoGetallonlinedevices().then((res) => {
                    if (res.code === 200) {
                      // 模拟设备JSON
                      var testData=[
                        {
                          "deviceCode": "202312121553002ZJM",
                          "deviceName": "172.31.52.152",
                          "deviceType": 2,
                          "ip": "172.31.52.152",
                          "port": 0,
                          "mac": null,
                          "isOnline": true,
                          "deviceVersions": null,
                          "id": "7ee0c200-8258-4540-9718-14e44f837c7d"
                        },
                        {
                          "deviceCode": "202312121553443fM",
                          "deviceName": "172.31.55.111",
                          "deviceType": 2,
                          "ip": "172.31.55.111",
                          "port": 0,
                          "mac": null,
                          "isOnline": true,
                          "deviceVersions": null,
                          "id": "7ee0c200-8258-4540-9718-562311558865"
                        },
                      ]
                      // this.devList=testData
                      // console.log('设备列表',this.devList);

                        if(res.data.length){
                          this.devList=res.data
                        }else{
                            this.devList=[]
                        }

                    }
                }).catch(err=>{

                }).finally(() => {
                    setTimeout(() => {
                        this.onlinedevLoading = false
                    }, 200)
                })
            },
            // 已选列表删除
            deleteSelectedList(row){
                console.log(row);
                if(row.id!==null){
                    this.selectedPersonList.map((item,index,arr)=>{
                        if(item.id==row.id){
                            // 删除当前点击项
                            arr.splice(index,1)
                            // 左侧组织树取消被点击的选中状态
                            this.$refs.orgInfoTree.setChecked(row.id,false)
                        }
                    })
                }
            },
            // 组织树复选框取消选中时，删除右侧已选列表中的数据
            orgInfocheck(data,val){
                console.log(data,val);
                console.log(this.selectedPersonList);
                if(!val){
                    if(this.selectedPersonList.length){
                        this.selectedPersonList.map((item,index,arr)=>{
                            if(item.id==data.id){
                                this.selectedPersonList.splice(index,1)
                            }
                        })
                    }
                }
            },
            // 清空全部已选择的人员
            clearAll(){
                // 确定要清空已选列表吗
                this.W.$myConfirm('warning', this.i18n.t('Are you sure you want to clear the selected list'))
                    .then(async () => {
                        this.selectedPersonList=[]
                        this.$refs.orgInfoTree.setCheckedKeys([]);
                    })
                    .catch(() => {
                    });
            },
            // 移动按钮
            moveRight(){
                this.moveLoading=true
                var checkedKeys=this.getOrginfoCheckedKeys()
                if(checkedKeys.length){
                    var result=[]
                    checkedKeys.map(item=>{
                        if(item.sex!==undefined){
                            result.push(item)
                        }
                    })
                    this.selectedPersonList=result
                    console.log('移动的数据', this.selectedPersonList);
                }else{
                    // 请在左侧选择要移动的人员!
                    this.W.$tips("warning", this.i18n.t('Please select the person to move on the left'));
                }
                setTimeout(()=>{
                    this.moveLoading=false
                },200)

            },
            // 获取组织树下选中的人员
            getOrginfoCheckedKeys(){
                return this.$refs.orgInfoTree.getCheckedNodes()
            },
            getCheckedNodes() {
                console.log(this.getOrginfoCheckedKeys());
            },
            getCheckedKeys() {
                console.log(this.$refs.orgInfoTree.getCheckedKeys());
            },
            /**
             * @description  获取部门人员树
             * @param :
             **/
            getdepartmenttree() {
                this.orgInfoTreeLoading = true
                this.$nextTick(async () => {
                    getdepartmenttree({IncludePersonInfo: true}).then((res) => {
                        if (res.code === 200) {
                            this.orgInfo= filterTreeData(res)
                          console.log(399,this.orgInfo);
                          // 显示左侧人员树
                            this.orgInfoDisplay=true
                            // console.log(JSON.stringify(this.orgInfo));
                            // console.log(339,this.filterNodeAndParent(this.orgInfo));
                            // console.log('orgInfo',this.orgInfo);
                        }
                    }).catch().finally(() => {
                        setTimeout(() => {
                            this.orgInfoTreeLoading = false
                        }, 500)
                    })

                });
            },

            // 搜索
            filterNode(value, data) {
                if (!value) return true
                return data.name.indexOf(value) !== -1
            },
            // filterNodeOrg(value, data){
            //     if (!value) return true;
            //     return data.name.indexOf(value) !== -1;
            // },
            filterNodeDev(value, data) {
                console.log(data);
                if (!value) return true;
                return data.deviceName.indexOf(value) !== -1;
            },
            handleCloseDialog() {
                this.$emit('update:distributeFlag', false);
                // this.$emit('update:editTableRow', null);
            },
            submitForm() {
                this.selectedDevList=this.$refs.devTree.getCheckedNodes()
                console.log('人员名单',this.selectedPersonList);
                console.log('在线设备', this.selectedDevList);
                if(!this.selectedPersonList.length){
                    // 请在左侧选择人员
                    this.W.$tips("warning", this.i18n.t('Please select personnel on the left side'));
                    return
                }
                if(!this.selectedDevList.length){
                    // 请在右侧选择要下发的设备
                    this.W.$tips("warning", this.i18n.t('Please select the device to be distributed on the right side'));
                    return
                }
                var selectedDevList=[],
                    selectedPersonList=[]
                this.selectedPersonList.map(item=>{
                    selectedPersonList.push(item.id)
                })
                this.selectedDevList.map(item=>{
                    selectedDevList.push(item.deviceCode)
                })
                this.saveloading=true
                this.personnelinfoSendpersondata({
                    "personnelInfoIds": selectedPersonList,
                    "deviceCods": selectedDevList
                })
            }
        },
        mounted(){
            this.orgInfoTreeLoading = true
            this.$nextTick(()=>{
                document.querySelector(".personList .empty-block").className+=" el-tree__empty-block"
                document.querySelector(".personList .empty-block .empty-text").className+=" el-tree__empty-text"
            })
            setTimeout(()=>{
                this.getOrgPersionCountFn=this.$parent.getOrgPersionCount

                var defaultPersonnel=[
                        {
                            id: -200,
                            name: this.i18n.t('All'),
                            children: []
                        }
                        ]
                defaultPersonnel[0].children=JSON.parse(JSON.stringify(this.editTableRow))
                // this.$set(this.defaultPersonnel[0],'children',JSON.parse(JSON.stringify(this.editTableRow)))
                this.orgInfo=defaultPersonnel
                console.log(481,defaultPersonnel);
                this.defaultExpandedArr=[defaultPersonnel[0].id]
                defaultPersonnel=null

                // this.orgInfo.map(item=>{
                //     item.isTop=1
                // })
                console.log('树数据',this.orgInfo);
                this.orgInfoTreeLoading = false
            },100)

            // 获取组织树
            // this.getdepartmenttree()
            // 获取在线设备
            this.deviceinfoGetallonlinedevices()

            // this.orgInfoHeight=700
        }
    }
</script>

<style lang="scss" scoped>
    .el-dialog-div {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 550px;
        overflow: hidden;

        .searchView {
            background: #e6eaf5;
            padding: 10px 15px;
            height: 52px;
            position: relative;
            box-sizing:border-box;
            :deep(.searchInput.el-input .el-input__inner) {
                border-radius: 50px;
                font-size: 14px;
            }
            :deep(.el-input__inner::placeholder) {
                font-size: 14px;
            }
            .searchInput {
                .el-input__inner{
                    font-size: 11px;
                }
            }
            i:hover{
                cursor: pointer;
            }
            &.centerPersonView{
                display: flex;
                justify-content: space-between;
                align-items: center;
                .searchInput{
                    margin-right: 10px;
                }
            }
        }
        .importSelect {

        }
        .orgTree{
            padding-left: 15px;
            padding-top: 15px;
        }
        .filter-tree,.orgTree{
            background-color: #f0f2f7;
        }
        .filter-tree {
            height: 500px;
        }
        .personView.filter-tree{
            overflow-y: scroll;
            position: relative;
            .personList{
                /*padding: 5px 15px;*/
                position: relative;
                border: 1px solid transparent;
                /*border-bottom: 1px solid #e5e8ef;*/
                box-sizing: border-box;
                i{
                    color: #babfcf;
                    float: right;
                    cursor: pointer;
                    margin-top: 3px;
                }
                &:hover{
                    /*background:#9aa9bf;*/
                    /*border: 1px solid #babfcf;*/
                }
                .centerName{
                    border: 0px solid red;
                    display: inline-block;
                    /*vertical-align: bottom;*/
                    width: 180px;
                }
            }
        }
        .treeView{
            width: 280px;
            height:100%;
            margin: 0 10px;
            position: relative;
            /*display: inline-block;*/
            /*border: 1px solid green;*/
            /*padding: 0 !important;*/
            box-sizing: border-box;
            &.person{
                margin-left: 100px;
            }
            #move{
                position: absolute;
                right: -75px;
                top: 45%;
            }
            .departmentName,.treeUserName{
                /*width: 150px;*/
                border: 0px solid red;
                display: inline-block;
                vertical-align: middle;

            }
            .treeUserName{
                width: 155px;
            }
            .departmentName{
                width: 170px;
            }
           .departmentName,.treeUserName,.personList .centerName{

                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap
            }
        }
    }
    #leftTree {
        /*border: 1px solid red;*/
        /*height: calc(100% - 90px);*/
        overflow-y: scroll !important;
        .userIcon,.orgIcon{
            color:#0666d2;
            &.female{
                color:#ff7700;
            }
        }
        .orgIcon{
            margin-right: 5px;
        }
        .treeTool{

            .treeToolIcon{
                color: #409eff;
                /*font-weight: bold;*/
                margin-left: 8px;
                vertical-align: middle;
            }
        }
    }
    .clearBtn{
        float: right;margin-top: 10px;margin-right: 5px
    }
    .custom-tree-node {

        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;

        /*position: relative;*/
        .treeToolIcon {
            color: #409eff;
            /*font-weight: bold;*/
            margin-left: 3px;
            vertical-align: middle;
        }

        .departmentName {
            width: 145px;
            border: 0px solid red;
            display: inline-block;

        }
    }
    ::v-deep .personList .empty-text{
        /*border: 1px solid red;*/
        display: inline-block;
        width: 100%;
    }
    ::v-deep .ellipsis{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    #devListTree{
      overflow-y: scroll !important;
      padding-bottom: 10px;
    }
</style>
